package me.shan.data.structure;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述：队列，数组实现
 *
 * @author liuchuang
 * @date 2021/7/6 15:59
 */
public class ArrayQueue {

    private int size;

    public int getSize() {
        return size;
    }

    public List<Integer> getElementDataList() {
        List<Integer> list = new ArrayList<>();

        int count = 0;
        int startIndex = headIndex;
        while (count < size) {
            list.add(elementData[startIndex]);
            startIndex++;
            if (startIndex == MAX_SIZE) {
                startIndex = 0;
            }
            count++;
        }
        return list;
    }

    private int headIndex;

    private int tailIndex;

    private final int[] elementData = new int[MAX_SIZE];

    /**
     * 最大支持的数组长度
     */
    private static final int MAX_SIZE = 100;

    public ArrayQueue() {
    }

    public void add(int value) throws Exception {
        if (size == MAX_SIZE) {
            throw new Exception("队列已满，不允许add操作");
        }
        elementData[tailIndex] = value;
        tailIndex++;
        if (tailIndex == MAX_SIZE) {
            tailIndex = 0;
        }
        size++;
    }

    public int remove() throws Exception {
        if (size == 0) {
            throw new Exception("队列为空，不允许remove操作");
        }
        int value = elementData[headIndex];
        headIndex++;
        if (headIndex == MAX_SIZE) {
            headIndex = 0;
        }
        size--;
        return value;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("ArrayQueue{size=");
        stringBuilder.append(size);
        stringBuilder.append(", elementData=[ ");
        if (size == 0) {
            stringBuilder.append("null ]}");
        } else {
            int count = 0;
            int startIndex = headIndex;
            while (count < size) {
                stringBuilder.append(elementData[startIndex]);
                if (count != size - 1) {
                    stringBuilder.append(", ");
                }
                startIndex++;
                if (startIndex == MAX_SIZE) {
                    startIndex = 0;
                }
                count++;
            }
            stringBuilder.append(" ]}");
        }
        return stringBuilder.toString();
    }

    public static void main(String[] args) throws Exception {
        ArrayQueue arrayQueue = new ArrayQueue();
        arrayQueue.add(1);
        arrayQueue.add(2);
        System.out.println(arrayQueue);
        System.out.println(arrayQueue.remove());
        System.out.println(arrayQueue.remove());
        arrayQueue.add(3);
        arrayQueue.add(4);
        arrayQueue.add(5);
        System.out.println(arrayQueue.remove());
        System.out.println(arrayQueue);
    }

}
